"""
    Author:
    Date: 2018-10-25

    微信开发的辅助类.
"""

import time

from django.http import HttpResponse

from entities import err
from entities import gm_mgr

from utils import util
from utils.log import Log
from utils import wx_config
from utils import wx_util


def _get_client_open_id(request):
    """ 获取用户的openid """
    dic = util.xml_to_dict(request.body)
    return dic['FromUserName']


def _build_return_dict(request):
    """ 构造基本的回复数据 """
    dic = util.xml_to_dict(request.body)
    to_user_name = dic['ToUserName']
    from_user_name = dic['FromUserName']

    return_dict = {
        'ToUserName': from_user_name,
        'FromUserName': to_user_name,
        'CreateTime': int(time.time()),
    }
    return return_dict


def _send_text_message_to_client(request, data):
    """ 给客户端发送文字信息 """
    if type(data) is dict:
        message_id = data['id']
        message = data['message']
        message = f'[{message_id}] {message}'
    else:
        message = data

    return_dict = _build_return_dict(request)
    return_dict['MsgType'] = 'text'
    return_dict['Content'] = message
    return HttpResponse(util.dict_to_xml(return_dict), content_type='application/xml')


def _send_news_message_to_client(request, title, description, pic_url, url):
    """ 发送图文消息给客户端 """
    articles = {
        'Title': title,
        'Description': description,
        'PicUrl': pic_url,
        'Url': url,
    }

    return_dict = _build_return_dict(request)
    return_dict['MsgType'] = 'news'
    return_dict['ArticleCount'] = 1
    return_dict['Articles'] = util.dict_to_xml(articles, [], 'item')
    return HttpResponse(util.dict_to_xml(return_dict, ['Articles']), content_type='application/xml')


def handle_wx_post(request):
    """ 处理微信post过来的信息 """
    dic = util.xml_to_dict(request.body)
    msg_type = dic['MsgType']

    if msg_type == 'text':
        return handle_text_msg(request)
    elif msg_type == 'event':
        return handle_event_msg(request)
    else:
        return _send_text_message_to_client(request, '👌')


def handle_text_msg(request):
    """ 处理文本消息 """
    dic = util.xml_to_dict(request.body)
    content = dic['Content']

    if content.lower() == 'download':
        title = 'YYZB'
        description = '快去下载YYZBAPP吧。'
        pic_url = 'http://ph3dknyq5.bkt.clouddn.com/download_app.png'
        url = wx_config.APP_DOWNLOAD_PAGE_IN_WX_URL
        return _send_news_message_to_client(request, title, description, pic_url, url)

    return _send_text_message_to_client(request, content)


def handle_event_scan_qr(request, scene_str):
    """ 处理用户扫码关注公众号 """
    event_values = scene_str.split(':')
    if len(event_values) != 2:
        Log.error(f'Invalid wechat scene str: {scene_str}')
        return _send_text_message_to_client(request, '👋')

    event_type, event_value = event_values
    if event_type == 'invite-gm':
        return handle_event_invite_gm(request, event_value)
    # elif event_type == 'invite-ga':
    #     return handle_event_invite_general_agent(request, event_value)
    # elif event_type == 'invite-agent':
    #     return handle_event_invite_agent(request, event_value)
    elif event_type == 'invite-user':
        return handle_event_invite_user(request, event_value)
    else:
        return _send_text_message_to_client(request, '👋')


def handle_event_subscribe(request):
    """ 处理用户主动关注公众号 """
    openid = _get_client_open_id(request)
    return _send_text_message_to_client(request, '感谢您关注我们的服务号。')


def handle_event_msg(request):
    """ 处理事件消息 """
    dic = util.xml_to_dict(request.body)
    event = dic['Event'].lower()
    event_key = dic.get('EventKey', None)

    if event == 'subscribe':
        if event_key:
            # 用户扫码关注
            scene_str = event_key[len('qrscene_'):]
            return handle_event_scan_qr(request, scene_str)
        else:
            # 用户主动关注
            return handle_event_subscribe(request)
    elif event == 'scan':
        scene_str = event_key
        return handle_event_scan_qr(request, scene_str)
    elif event in ['click']:
        print(f'click event: {event_key}')
        # if event_key == 'V1001_AGENT_SYSTEM':
        #     # 产品推广
        #     return HttpResponseRedirect('/gma/wx/mp/agent/home/')
        # elif event_key == 'V1002_RED_PACK':
        #     # 领取红包
        #     return HttpResponseRedirect('/gma/wx/mp/withdraw/')
        # elif event_key == 'V1003_ABOUT_US':
        #     # 关于我们
        #     return HttpResponseRedirect('/gma/wx/mp/about/')
        # else:
        #     return _send_text_message_to_client(request, '👋')
        return _send_text_message_to_client(request, '👋')
    else:
        return _send_text_message_to_client(request, '👋')


def handle_event_invite_gm(request, event_value):
    """ 处理邀请GM的事件 """
    inviter_name = event_value
    openid = _get_client_open_id(request)

    # 获取用户信息
    user_info = wx_util.WechatApi.get_user_info(openid)
    if user_info is None:
        return _send_text_message_to_client(request, '获取用户信息失败！')

    # 查找GM是否已经存在
    gm = gm_mgr.get_gm(openid)
    if gm is not None:
        return _send_text_message_to_client(request, '你已经是管理员了！')

    # 创建新的GM
    gm = gm_mgr.create_gm(openid, user_info)
    if gm is None:
        return _send_text_message_to_client(request, '创建管理员失败!')

    return _send_text_message_to_client(request, f'已收到你的申请, 请等待{inviter_name}的审批！')


def handle_event_invite_user(request, event_value):
    """ 处理邀请用户的事件 """
    inviter_openid = event_value
    openid = _get_client_open_id(request)

    # 获取用户信息
    user_info = wx_util.WechatApi.get_user_info(openid)
    if user_info is None:
        return _send_text_message_to_client(request, err.ERROR_GET_USER_INFO_FAILED)

    # 跳转到下载页面
    title = 'YYZB'
    description = '快去下载YYZBAPP吧。'
    pic_url = 'http://ph3dknyq5.bkt.clouddn.com/download_app.png'
    url = wx_config.APP_DOWNLOAD_PAGE_IN_WX_URL
    return _send_news_message_to_client(request, title, description, pic_url, url)


if __name__ == '__main__':
    print('ok')
